<script setup lang="ts">
import { ref, onMounted, toRefs, reactive } from "vue";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import lineChart from "../lineChart/index.vue";
import { spcquerySpcAnalysis } from "@/api/spc";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { queryChildByTypeCodeAndItemValue } from "@/api/machineClass";

const loading = ref(false);

const router = useRouter();

const state = reactive<any>({
  spcJobList: [],
  weatherSpcJobList: [],
  dataDetailTable: [],
  dateRangeSpcDetail: [],
  weatherOptions: {},
  querySpcDetailParams: {}
});

const { dataDetailTable, dateRangeSpcDetail, spcJobList, weatherSpcJobList, querySpcDetailParams, weatherOptions } = toRefs(state);

const initSpcDate = () => {
  const date = new Date();
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let hour = date.getHours() < 10 ? "0" + date.getHours().toString() : date.getHours().toString();
  let minites = date.getMinutes() < 10 ? "0" + date.getMinutes().toString() : date.getMinutes().toString();
  let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds().toString() : date.getSeconds().toString();
  let lastda = date.getDate() < 10 ? "0" + (date.getDate() + 1).toString() : (date.getDate() + 1).toString();
  let year = date.getFullYear();
  let lastYear = date.getFullYear() - 1;
  return [`${year}-${month}-${da}`, `${year}-${month}-${da}`]; // 近一年时间范围
  // return [`${year}-${month}-${lastda} 00:00:00`, `${year}-${month}-${da} ${hour}:${minites}:${seconds}`]; // 近一年时间范围
};

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};

const turnBack = () => {
  router.go(-1);
};

// 查询明细
const querySpc = async () => {
  const params = {
    jobIdList: [...spcJobList.value],
    timePeriod: "hour",
    startTime: dateRangeSpcDetail.value[0] + " 00:00:00",
    endTime: dateRangeSpcDetail.value[1] + " 23:59:59"
  };
  const res: any = await spcquerySpcAnalysis(params);
  const arr = res.filter((item: any) => spcJobList.value.indexOf(item.jobId) !== -1); // 过滤出有数据的
  const spcList = arr.map((item: any) => {
    item.startTime = dateRangeSpcDetail.value[0];
    item.endTime = dateRangeSpcDetail.value[1];
    item.pointValues = item.pointValues ? item.pointValues : []; // null时判断，有数据可放开
    return {
      ...item
    };
  });
  dataDetailTable.value = spcList;
  const obj = spcList[0];
  // weatherOptions.value = obj;

  const yAxis =
    spcList &&
    spcList.map((item, index) => {
      return {
        type: "value",
        name: obj.indicatorName,
        nameLocation: "middle", //居中
        offset: (0 + index) * 50,
        nameGap: 70, //轴线距离
        nameRotate: 90, //字体选择角度
        axisLine: {
          show: true,
          lineStyle: {
            type: "solid"
          }
        }
      };
    });
  const series =
    spcList &&
    spcList.map((obj, ind) => {
      return {
        data: obj && obj.pointValues.length > 0 ? obj.pointValues.map(item => item.value) : [],
        type: "line",
        name: obj.indicatorName,
        yAxisIndex: ind,
        symbol: "none",
        markLine: {
          symbol: "none",
          data: [
            {
              name: "USL值",
              yAxis: Number(obj.uslValue),
              lineStyle: {
                color: "#A600FF",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `USL值${obj.uslValue}`,
                color: "#A600FF",
                fontWeight: 600
              }
            },
            {
              name: "UCL值",
              yAxis: Number(obj.uclValue),
              lineStyle: {
                color: "#FF0000",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `UCL值${obj.uclValue}`,
                color: "#FF0000",
                fontWeight: 600
              }
            },
            {
              name: "UWL值",
              yAxis: Number(obj.uwlValue),
              lineStyle: {
                color: "#FF9900",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `UWL值${obj.uwlValue}`,
                color: "#FF9900",
                fontWeight: 600
              }
            },
            {
              name: "Target值",
              yAxis: Number(obj.targetValue),
              lineStyle: {
                color: "#00E272",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `Target值${obj.targetValue}`,
                color: "#00E272",
                fontWeight: 600
              }
            },
            {
              name: "LWL值",
              yAxis: Number(obj.lwlValue),
              lineStyle: {
                color: "#FF9900",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `LWL值${obj.lwlValue}`,
                color: "#FF9900",
                fontWeight: 600
              }
            },
            {
              name: "LCL值",
              yAxis: Number(obj.lclValue),
              lineStyle: {
                color: "#FF0000",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `LCL值${obj.lclValue}`,
                color: "#FF0000",
                fontWeight: 600
              }
            },
            {
              name: "LSL值",
              yAxis: Number(obj.lslValue),
              lineStyle: {
                color: "#A600FF",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `LSL值${obj.lslValue}`,
                color: "#A600FF",
                fontWeight: 600
              }
            }
          ]
        }
      };
    });
  const legendData = spcList && spcList.map(item => item.indicatorName);
  const option = {
    color: "#ccc",
    grid: {
      left: "60px",
      top: "40px",
      right: "100px",
      bottom: "5%",
      containLabel: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      data: legendData,
      orient: "horizontal",
      bottom: "0"
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data:
        obj && obj.pointValues.length > 0
          ? obj.pointValues.map(item => formatDate(item.time))
          : ["11:00", "12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: yAxis,
    series: series
  };
  weatherOptions.value = option;
};

// 重置筛选条件
const resetSpc = async () => {
  dateRangeSpcDetail.value = initSpcDate();
  spcJobList.value = [weatherSpcJobList.value.filter(item => item.itemValue === "WEATHER_TEMP_DRY")[0].itemDesc];
  querySpc();
};

const gotoSpc = () => {
  router.push({ path: "/machine/spc/spcseetings" });
};

onMounted(async () => {
  const res: any = await queryChildByTypeCodeAndItemValue({
    typeCode: "OUTDOOR_WEATHER"
  });
  weatherSpcJobList.value = res;
  spcJobList.value = [weatherSpcJobList.value.filter(item => item.itemValue === "WEATHER_TEMP_DRY")[0].itemDesc];
  dateRangeSpcDetail.value = initSpcDate();
  querySpc();
});
</script>

<template>
  <div class="spc_detail">
    <div class="top_turnback">
      <px-button type="primary" :icon="ArrowLeft" @click="turnBack">返回</px-button>
    </div>
    <div class="import-bottle-title">
      <px-icon color="#F59E0B"><WarningFilled /></px-icon>
      &nbsp;指标曲线请先设置SPC
      <span class="download" @click="gotoSpc"> 去设置 </span>
    </div>
    <px-form ref="querySpcDetailRef" :model="querySpcDetailParams" :inline="true" label-width="68px">
      <px-form-item label="指标类型" prop="alarmLevel">
        <px-checkbox-group v-model="spcJobList">
          <px-checkbox v-for="item in weatherSpcJobList" :key="item.id" :label="item.itemDesc">{{ item.itemName }}</px-checkbox>
        </px-checkbox-group>
      </px-form-item>
      <px-form-item label="时间日期" style="width: 460px">
        <px-date-picker
          v-model="dateRangeSpcDetail"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </px-form-item>
      <px-form-item>
        <px-button type="primary" @click="querySpc">查询</px-button>
        <px-button @click="resetSpc">重置</px-button>
      </px-form-item>
    </px-form>
    <div class="con_spc">
      <div class="spc_com">
        <lineChart ref="spcChartWeatherRef" :key="new Date().getTime()" :width="800" :options="weatherOptions" />
      </div>
    </div>
    <barTitle title="数据明细" />
    <px-table v-loading="loading" max-height="389" :header-cell-style="{ background: '#e7eefb', color: '#000' }" border :data="dataDetailTable">
      <px-table-column label="时间" prop="startTime" />
      <px-table-column label="大气指标类型" prop="indicatorName" />
      <px-table-column label="值" prop="avgValue" />
    </px-table>
  </div>
</template>

<style lang="scss" scoped>
.spc_detail {
  width: 100%;
  min-width: 1300px;
  padding: 16px 24px;
  background-color: white;

  .con_spc {
    display: flex;
    justify-content: space-between;
    margin-top: 16px;

    .spc_com {
      position: relative;
      flex: 1;

      .edit_form {
        display: flex;
        flex-flow: row nowrap;
        gap: 10px;
      }

      .edit_y1 {
        position: absolute;
        cursor: pointer;
      }
    }
  }

  .import-bottle-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding-left: 16px;
    margin: 16px 0;
    line-height: 1;
    color: #333;
    background-color: #fef5e6;
    border: 1px solid #f7b648;
    border-radius: 6px;

    .download {
      margin-left: 8px;
      color: #3b82f6;
      cursor: pointer;
    }
  }
}
</style>
